const express = require("express");
const router = express.Router();
const db = require('../../db/index');
const bcrypt = require("bcryptjs");  //加密密码

router.post('/register', (req, res) => {

    let { username, password, code } = req.body;
    const captcha = req.session.captcha;
    if (code.toUpperCase() == captcha.toUpperCase()) {//验证码比对
        db.query('select * from user where username = ? ', [username], (err, data) => {
            if (err) throw err;

            if (data.length > 0) {
                res.send({ code: 0, data: null, msg: '用户名已使用' });
            } else {
                let passwordEnd = bcrypt.hashSync(password, 10); //  加密密码
                let time = new Date();
                db.query('insert into user (username,password,time) values (?,?,?)', [username, passwordEnd, time], (err, data) => {
                    if (err) err;
                    res.send({ code: 200, data: null, msg: '注册成功' });
                });
            }
        });

    } else {
        res.send({ code: 0, data: null, msg: '验证码不正确' });
    }

});

module.exports = router;